import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class GiteeDataPage extends StatefulWidget {
  const GiteeDataPage({Key? key}) : super(key: key);

  @override
  State<GiteeDataPage> createState() => _GiteeDataPageState();
}

class _GiteeDataPageState extends State<GiteeDataPage> {
  List<dynamic>? data;
  String? error;

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  Future<void> fetchData() async {
    final dio = Dio();
    final url = 'https://gitee.com/Leann_2023/network_request/raw/main/lib/data.json'; //  Gitee raw 地址
    try {
      final response = await dio.get(url);
      setState(() {
        data = response.data;
        error = null;
      });
    } catch (e) {
      setState(() {
        error = e.toString();
        data = null;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Gitee Dio 示例')),
      body: Center(
        child: error != null
            ? Text('请求出错: $error')
            : data == null
                ? const CircularProgressIndicator()
                : ListView.builder(
                    itemCount: data!.length,
                    itemBuilder: (context, index) {
                      final item = data![index];
                      return ListTile(
                        title: Text(item['title'] ?? '无标题'),
                        subtitle: Text(item['desc'] ?? ''),
                      );
                    },
                  ),
      ),
    );
  }
}